import Taro, { ShareAppMessageReturn, useShareAppMessage } from '@tarojs/taro';
import { useEffect } from 'react';
import { Provider } from 'react-redux';
import 'taro-ui/dist/style/index.scss';
import './app.less';
import dva from './dva';
import models from './models';
import { initGlobalData } from './pages/util/data';
import './pages/util/string';
import RandomString from './pages/util/string';
import { wxLogin } from './services/api-user';

const dvaApp = dva.createApp({
	initialState: {},
	models: models,
});
const store = dvaApp.getStore();

const App = (props: any) => {

	useEffect(() => {
		Taro.cloud.init({
			env: 'gpt-2g802u5l527946e6',
			// env: 'prod-5gbjvrp363ec62e6',
			traceUser: true
		})

		let clientId = Taro.getStorageSync('clientId');
		clientId ? console.log('存在clientId信息：', clientId) : Taro.setStorageSync('clientId', RandomString(10));

		initGlobalData()

		// 检查用户登录状态是否过期
		let userToken = Taro.getStorageSync('userToken');
		console.log('打印历史token:', userToken)

		if (!userToken) {
			Taro.login({
				success: ((loginRes: Taro.login.SuccessCallbackResult) => {
					console.log('wx.login登录成功:', loginRes)
					if (loginRes.code) {
						wxLogin({ code: loginRes.code }).then(res => { // 请求服务获取登录态信息
							if (res.data?.code === 'SUCCESS') {
								console.log('server.login登录成功:', res)
								Taro.setStorageSync('userToken', res.data?.data?.token)
							}
						})
					}
				}),
				fail: ((res: Taro.General.CallbackResult) => { console.log('登录失败:', res) })
			})
		}

	}, [])



	useShareAppMessage(() => {
		return {
			title: '免费AI聊天和绘画,用它就够了',
			path: '/pages/community/index',
			imageUrl: "http://ys-aigc.oss-cn-beijing.aliyuncs.com/mj/jTKOUa.jpg?x-oss-process=image/crop,w_1024,h_1024,y_0,g_nw"
		} as ShareAppMessageReturn
	})

	return (
		<Provider store={store}>{props.children}</Provider>
	)
}

export default App
